<template>
  <div class="versionView-container">
    <div class="header">
      {{ sceneNodeName }}
    </div>
    <div class="BlackHole-container">
      <div class="spin-warp" v-if="loading">
        <a-spin size="large" />
      </div>
      <div class="bim-container" ref="blackHoleContainer"></div>
    </div>
  </div>
</template>

<script>
//预览模型和cad
import { axios } from "@/utils/request";
import { canvasHolder } from "@/blackHoleTools/CanvasHolder";
import { releaseEngine, initialSDKModule } from "@/blackHoleTools/Engine";
import { mapGetters } from "vuex";
import { getModalTreeElemIdsById } from "@/api/bim";
export default {
  data() {
    return {
      viewData: {},
      cadSource: {},
      sceneNodeName: "",
      loading: false,
    };
  },
  computed: {
    ...mapGetters(["blackHoleAssetsPreFetch", "blackHoleRESystemCreated"]),
  },
  watch: {
    blackHoleAssetsPreFetch: {
      handler(val) {
        this.$nextTick((_) => {
          if (val) {
            initialSDKModule();
          }
        });
      },
      immediate: true,
    },

    blackHoleRESystemCreated: {
      handler(val) {
        if (val) {
          this.loading = true;
          this.$nextTick((_) => {
            let { name, dataSetId, cadId } = this.$route.query;
            let pageName = name || "3D模型预览";
            this.sceneNodeName = pageName;
            document.title = pageName;
            Promise.all([
              this.getSetModelData(dataSetId),
              this.getCADModelData(cadId),
            ])
              .then((res) => {
                let [viewData, cadSource] = res;
                if (
                  (viewData && viewData?.length > 0) ||
                  (cadSource && cadSource?.resourcesAddress)
                ) {
                  this.viewData = viewData;
                  this.cadSource = cadSource;
                  this.addEventListener();
                  this.onEngineCreated();
                }
              })
              .finally((_) => {});
          });
        }
      },
    },
  },
  methods: {
    //查询BIM地址
    getSetModelData(dataSetId = "") {
      return new Promise((resolve, reject) => {
        if (!dataSetId) {
          resolve(null);
        } else {
          axios
            .post(
              `/probusiness/blackHole3D/project/dataSet/viewDataSetModel`,
              {
                dataSetIds: [dataSetId],
              },
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              let viewData = res?.data?.modelData ?? [];

              resolve(viewData);
            })
            .catch((_) => {
              this.viewData = [];
              reject();
            });
        }
      });
    },

    //查询CAD资源地址
    getCADModelData(uuid = "") {
      return new Promise((resolve, reject) => {
        if (!uuid) {
          resolve(null);
        } else {
          axios
            .post(
              `/probusiness/bimCadFile/project/cadFile/list?uuid=${uuid}`,
              {},
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              let cadSource = res?.data?.[0] ?? {};
              resolve(cadSource);
            })
            .catch((_) => {
              this.cadSource = {};
              reject();
            })
            .finally((_) => {});
        }
      });
    },

    //系统引擎创建完成回调【加载模型资源】
    onEngineCreated() {
      let { viewData, cadSource } = this;
      let dom = this.$refs.blackHoleContainer;
      let BlackHole3D = window.BlackHole3D;
      canvasHolder.moveCanvasToTarget(this.$refs.blackHoleContainer);
      BlackHole3D.m_re_em_window_width = dom.clientWidth;
      BlackHole3D.m_re_em_window_height = dom.clientHeight;
      BlackHole3D.Coordinate.setEngineWorldCRS("EPSG:3857");
      let dataSetSources = [];
      viewData.forEach((item) => {
        let { dataSetId, resourcesAddress } = item;
        dataSetSources.push({
          dataSetId,
          resourcesAddress,
          useTransInfo: true,
          transInfo: [
            [1, 1, 1],
            [0, 0, 0, 1],
            [0, 0, 0],
          ],
        });
      });
      //开始加载一个或多个模型资源
      dataSetSources.length > 0 &&
        BlackHole3D.Model.loadDataSet(dataSetSources);
      //加载CAD资源
      cadSource?.resourcesAddress &&
        BlackHole3D.CAD.loadCAD(
          cadSource.resourcesAddress,
          BlackHole3D.RECadUnitEm.CAD_UNIT_Millimeter,
          1.0
        );
    },

    //bim事件监听
    addEventListener() {
      //场景模型加载完成回调
      document.addEventListener("REDataSetLoadFinish", (_) => {
        //设置系统UI
        this.setSystemUI();
        //设置模型透明度
        let { dataSetId, nodeId } = this.$route.query;
        if (nodeId) {
          BlackHole3D.BIM.setElemAlpha(dataSetId, [], 0);
          this.getElemIds(dataSetId, nodeId);
        } else {
          this.loading = false;
        }
      });
      window.addEventListener("resize", this.onResize);

      //监听cad文件加载完成
      document.addEventListener("RECADLoadFinish", (isSuccess) => {
        if (isSuccess) {
          this.loading = false;
          if (this.viewData.length > 0) {
            //设置横向双屏显示，左边为CAD，右边为BIM场景
            BlackHole3D.setViewMode(
              BlackHole3D.REVpTypeEm.CAD,
              BlackHole3D.REVpTypeEm.BIM,
              BlackHole3D.REVpRankEm.LR
            );
          } else {
            //设置横向单屏显示CAD
            BlackHole3D.setViewMode(
              BlackHole3D.REVpTypeEm.CAD,
              BlackHole3D.REVpTypeEm.None,
              BlackHole3D.REVpRankEm.Single
            );
          }
        } else {
          console.log(
            "CAD加载失败！！！！！！！！！！！！！！！！！！！！！！！"
          );
        }
      });
    },

    //查询节点对应的构件id集合
    getElemIds(dataSetId, nodeId) {
      let dataSets = [
        {
          childNodeId: nodeId,
          dataSetId,
        },
      ];
      return new Promise((resolve, reject) => {
        getModalTreeElemIdsById({ dataSets })
          .then((res) => {
            let { data } = res;
            let ids = data?.[0]?.childNodeIds ?? [];
            BlackHole3D.BIM.setElemAlpha(dataSetId, ids, 255);
            resolve();
          })
          .catch((_) => {
            resolve([]);
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //设置系统UI
    setSystemUI() {
      try {
        BlackHole3D.Graphics.setGeoCoordVisible(true);
        BlackHole3D.Graphics.setSysUIPanelVisible(true);
        BlackHole3D.Graphics.setSysPanelUIDockArea(3);
        BlackHole3D.Camera.resetCamLocate();
        BlackHole3D.Camera.resetCamBound();
      } catch (error) {}
    },

    //监听窗口尺寸变化
    onResize() {
      let box = this.$refs["blackHoleContainer"];
      if (box) {
        window.BlackHole3D.m_re_em_window_width = window.innerWidth;
        window.BlackHole3D.m_re_em_window_height = window.innerHeight;
      }
    },
  },
  beforeDestroy() {
    releaseEngine();
  },
};
</script>

<style lang="less" scoped>
.versionView-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .header {
    padding: 0 20px;
    line-height: 60px;
    font-size: 20px;
    font-weight: 400;
    color: #ffffff;
    background-color: #2f2f2f;
    flex-shrink: 0;
  }
  .BlackHole-container {
    flex: 1;
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    .spin-warp {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    .bim-container {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
